package com.cungmua.app.base;

import android.app.AlertDialog;
import android.content.DialogInterface;

import com.cungmua.app.handler.BaseAuthenticatedRequestHandler;
import com.cungmua.app.model.User;
import com.cungmua.app.model.request.LoginRequest;
import com.cungmua.app.utils.JsonUtils;
import com.cungmua.app.utils.PrefUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Created by kelvin.nguyen on 6/16/14.
 */
public abstract class BaseAuthenticatedActivity extends BaseRequestActivity implements BaseAuthenticatedRequestHandler{
    @Override
    public LoginRequest getLastLoginRequest() {
        LoginRequest loginRequest = null;
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            String json = PrefUtils.readPreferences(this, LOGIN_REQUEST_KEY, "");
            loginRequest = mapper.readValue(json, LoginRequest.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return loginRequest;
    }

    @Override
    public void reLoginFailed(final String reason) {
        setCurrentUser(User.defaultUser());

        if (!reason.isEmpty()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog dialog = new AlertDialog.Builder(BaseAuthenticatedActivity.this)
                            .setMessage(reason).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                    login();
                                }
                            }).show();
                }
            });
            return;
        }
        login();
    }
}
